package kr.hkit.android_bookmgr.activity;

import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import kr.hkit.android_bookmgr.R;
import kr.hkit.android_bookmgr.DAO.BookDAO;
import kr.hkit.android_bookmgr.util.ImageUtil;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class BookMemoEditActivity extends Activity {

	private BookDAO mMemoMgr;
	static final int CALL_CAMERA = 0;
	static final int CALL_GALLERY = 1;
	private String mPathCamera = null;
	private String mPathGallery = null;
	private String mRealPathGallery = null;
	private int mYear, mMonth, mDay, mHour, mMin, mSec;
	private int code = -1;
	private ImageView ivMemoimg;
	private EditText etWritedate, etReview, etWordspage, etWords;
	private String memoimg;
	private int memoimgtype, memoId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.bookmemo_edit_activity);
		
		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true); 
		mActionBar.setHomeButtonEnabled(true);
		
		Intent intent = getIntent();
		memoId = intent.getIntExtra("memoId", -1);
		String writedate= intent.getStringExtra("writedate");
		String review= intent.getStringExtra("review");
		int wordspage= intent.getIntExtra("wordspage", 0);
		String words= intent.getStringExtra("words");
		memoimg = intent.getStringExtra("memoimg");
		memoimgtype = intent.getIntExtra("memoimgtype", -1);
		
		etWritedate = (EditText) findViewById(R.id.bookmemo_edit_writedate);
		etWritedate.setOnFocusChangeListener(mOnFocusChangeListener);
		etReview = (EditText) findViewById(R.id.bookmemo_edit_review);
		etWordspage = (EditText) findViewById(R.id.bookmemo_edit_wordspage);
		etWords = (EditText) findViewById(R.id.bookmemo_edit_words);
		
		etWritedate.setText(writedate); // 날짜!!! 
		etReview.setText(review);
		etWordspage.setText(wordspage+"");
		etWords.setText(words);
		
		ivMemoimg = (ImageView) findViewById(R.id.bookmemo_edit_memoimg);
		ImageUtil.imageLoader(BookMemoEditActivity.this);
		DisplayImageOptions options = ImageUtil.dispalyOptions();
		if (memoimgtype==0){ //직찍
			ImageLoader.getInstance().displayImage("file:///"+memoimg, ivMemoimg, options);
		}else if(memoimgtype==1){ //갤러리
			ImageLoader.getInstance().displayImage("content://media/"+memoimg, ivMemoimg, options);
		}
		
		calendar();
		
		mPathCamera = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+mYear+"_"+(mMonth+1)+"_"+mDay+"_"+mHour+"_"+mMin+"_"+mSec+".jpg";
		
	}//onCreate
	
	private void calendar(){
		
		Calendar cal = new GregorianCalendar();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
		mHour = cal.get(Calendar.HOUR_OF_DAY);
		mMin = cal.get(Calendar.MINUTE);
		mSec = cal.get(Calendar.SECOND);
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.bookmemo_edit_actionbarmenu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent=null;
		switch(item.getItemId()){
		case R.id.bookmemo_edit_camera: //카메라호출
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPathCamera)));
			startActivityForResult(intent, CALL_CAMERA);
			break;
		
		case R.id.bookmemo_edit_gallery: //갤러리
			intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
			startActivityForResult(intent, CALL_GALLERY);
			break;
		case android.R.id.home:
			intent = new Intent(this, BookListActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 액티비티 쌓이지 않기위해.
			startActivity(intent);
			break;
		
		}
		return super.onOptionsItemSelected(item);
	}//onOptionsItemSelected
	
	
	// 카메라 결과
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			  
			code = requestCode;
			
			if(resultCode==RESULT_OK){
				switch(requestCode){
				case CALL_CAMERA: //카메라 호출 촬영결과
					
					updateImageView();
					//Toast.makeText(this, mPathCamera, Toast.LENGTH_LONG).show();
					break;
					
				case CALL_GALLERY: //갤러리 호출 결과
					
					Uri mImageUri = data.getData();
					mPathGallery= data.getData().getPath();//이거내꺼였음...
					mRealPathGallery = getPath(mImageUri);//이거하면 원 주소 나옴!!
					Log.d("path", "갤러리: "+mRealPathGallery);
					updateImageView();
					break;
					
				}// switch
			}// if
		}// onActivityResult
	
	
	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.bookmemo_edit_btn: //메모수정 DB 
			
			ContentValues updateRowValues = new ContentValues();
			updateRowValues.put("writedate", etWritedate.getText().toString());
			updateRowValues.put("review", etReview.getText().toString());
			updateRowValues.put("wordspage", etWordspage.getText().toString());
			updateRowValues.put("words", etWords.getText().toString());
			if(code==0){
				updateRowValues.put("memoimg", mPathCamera.trim()); //직찍 경로
				updateRowValues.put("memoimgtype", 0); //imgtype 0이면 직찍
			}else if(code==1){
				updateRowValues.put("memoimg", mPathGallery.trim()); //갤러리 경로
				updateRowValues.put("memoimgtype", 1); //imgtype 1이면  갤러리
			}else if(code==-1){//사진이 없을경우 메이비
				updateRowValues.put("memoimg", memoimg);//원래사진...?
				updateRowValues.put("memoimgtype", memoimgtype);
			}
			
			
			mMemoMgr = BookDAO.getInstance(BookMemoEditActivity.this);
			
			String whereClause="_id=?";
			String[] whereArgs = new String[1];
			whereArgs[0] = Integer.toString(memoId);//id는? 
			mMemoMgr.updateMemo(updateRowValues, whereClause, whereArgs);
			
			Toast.makeText(BookMemoEditActivity.this, "수정되었습니다.", Toast.LENGTH_SHORT).show();
			
			finish();
			break;
		case R.id.bookmemo_edit_canclebtn:
			finish();
			break;
		}
	}// mOnClick
	
	//독서시작일 독서완료일 textview 포커스 datepicker
    OnFocusChangeListener mOnFocusChangeListener = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			
			if(hasFocus)
				new DatePickerDialog(BookMemoEditActivity.this, mDateSetListener, mYear, mMonth, mDay).show();
		}
	};//OnFocusChangeListener
	
	
	DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			
			etWritedate.setText(String.format("%d/%02d/%d", mYear, mMonth+1, mDay));
			
		}
	};//DatePickerDialog
	
	
	 private String getPath(Uri uri) {  
	        String[] projection = { MediaStore.Images.Media.DATA };  
	  
	        Cursor cursor = managedQuery(uri, projection, null, null, null);  
	        int column_index = cursor  
	        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
	        cursor.moveToFirst();  
	  
	        return cursor.getString(column_index);  
	    }  
	 
	 
	 private void updateImageView() {  
		 
		 if(code==CALL_CAMERA){
			 
			 
			int degree = ImageUtil.GetExifOrientation(mPathCamera);
			Bitmap resizeBitmap = ImageUtil.loadBackgroundBitmap(BookMemoEditActivity.this, mPathCamera);

			if (degree != 0) {
				Bitmap rotateBitmap = ImageUtil.GetRotatedBitmap(resizeBitmap,degree);
				ivMemoimg.setImageBitmap(rotateBitmap);
				ivMemoimg.setScaleType(ImageView.ScaleType.FIT_XY);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 380);
				ivMemoimg.setLayoutParams(param);
				
			} else {// 0이면 안돌려도됨
				
				ivMemoimg.setImageBitmap(resizeBitmap);
				ivMemoimg.setScaleType(ImageView.ScaleType.FIT_XY);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 380); //계산해서넣었음ㅋㅋ
				ivMemoimg.setLayoutParams(param);
			}
			 
		 }else if (code==CALL_GALLERY){
			 
	        int degree = ImageUtil.GetExifOrientation(mRealPathGallery);  
	        Bitmap resizeBitmap = ImageUtil.loadBackgroundBitmap(BookMemoEditActivity.this, mRealPathGallery);  
	        
	        if(degree!=0){
	        	Bitmap rotateBitmap = ImageUtil.GetRotatedBitmap(resizeBitmap, degree);  
	        	ivMemoimg.setImageBitmap(rotateBitmap);  
	        	ivMemoimg.setScaleType(ImageView.ScaleType.FIT_XY);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 380);
				ivMemoimg.setLayoutParams(param);
				
	        }else{//0이면 안돌려도됨
	        	ivMemoimg.setImageBitmap(resizeBitmap);
	        	ivMemoimg.setScaleType(ImageView.ScaleType.FIT_XY);
				LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(300, 380); //계산해서넣었음ㅋㅋ
				ivMemoimg.setLayoutParams(param);
				
	        }//inner if~else
		 }//if~else
	    } //updateImageView() 
	
	
}
